    <?php
/**
 * Created by PhpStorm.
 * User: l
 * Date: 2018/10/30
 * Time: 17:10
 */
use app\assets\AppAsset;
use app\common\CommonHelper;

$base = Yii::$app->request->baseUrl;
AppAsset::addCss($this,$base . '/app/css/dynamic-detail.css?V=0.0.9');

$model = new CommonHelper();
$baseUrlHead  = $model->getIp();
?>
<div class="dynamic-gift-comment-container">

    <p class="top-title">评论详情</p>

    <p class="item-title">一级评论</p>
    <div class="comment-item">
        <img class="comment-avatar" src="<?= $first_comment['user']['user_avatar']?>">
        <div class="story">
            <div class="opbtn" style="cursor: pointer" comment-content="<?= $first_comment['comment_content']?>" type="2" onclick="showPraiseDialog(this,<?= $first_comment['comment_id']?>)"><img class="like-icon" src="<?= $base?>/app/images/dynamic/rc_icon_seduce_dynamic_details_praise.png"><?= $first_comment['like_count']?></div>
            <p class="story_t"><?= $first_comment['like_count']."(".$first_comment['user']['user_sex'] == 0?"女":"男".$first_comment['user']['city_name'].")"?>&nbsp;<?= $first_comment['gmt_create']?></p>
            <p class="story_m"><?= $first_comment['comment_content']?></p>
            <p>
                <span class="story_r" comment-content="<?= $first_comment['comment_content']?>" onclick="showCommentDialog(this,<?= $first_comment['comment_id']?>)">回复</span>

                    <span class="story_r" style="color: red;" comment-content="<?= $first_comment['comment_content']?>" onclick="operateController.operateFunc(<?= $first_comment['comment_id']?>)">删除</span>
            </p>
        </div>
        <div class="clear"></div>
    </div>

    <p class="item-title">多级评论</p>
    <div class="comment-item-container">
    </div>

    <table id="table2" hidden="hidden"></table>
</div>

<div id="commentDialog" class="dialog-operate" hidden="hidden">
    <div class="operate-box">
        <p>评论内容：</p>

        <textarea id="operateContent" placeholder="输入评论内容" class="operate-content" title="operate"></textarea>

        <div style="margin-top: 1.67rem"></div>

        <span>回复者：</span>

        <span id="dynamicUserId" class="user-select">
            未选择马甲
        </span>

        <span class="update-vest" onclick="showVestDialog('dynamicUserId')">更换</span>

        <div class="footer-div">
            <div class="button-div" onclick="confirmComment()">确定</div>
            <div class="button-div" style="margin-left: 1.5rem" onclick="hideCommentDialog()">取消</div>
        </div>
    </div>
</div>

<div id="praiseDialog" class="dialog-operate" hidden="hidden">
    <div class="operate-box">
        <p>点赞内容：</p>

        <div style="margin-top: 1.67rem"></div>

        <span>回复者：</span>

        <span id="praiseUserId" class="user-select">
            未选择马甲
        </span>

        <span class="update-vest" onclick="showVestDialog('praiseUserId')">更换</span>

        <div class="footer-div">
            <div class="button-div" onclick="confirmPraise()">确定</div>
            <div class="button-div" style="margin-left: 1.5rem" onclick="hidePraiseDialog()">取消</div>
        </div>
    </div>
</div>

<div id="chooseUser" class="dialog-operate" hidden="hidden">
    <div class="user-item-container">
        <p class="dialog-title">选择马甲<img style="float: right;margin-top: 6px;cursor: pointer" src="<?= $base?>/app/images/close.png" onclick="hideVestDialog()"></p>
        <div class="clear"></div>
        <div class="divider-line"></div>
        <div class="vest-box">
        </div>

        <div class="clear"></div>
        <table id="table3" hidden="hidden"></table>
    </div>

</div>

<script>
    var baseUrl = '<?= $baseUrlHead?>';
    var dynamicId = '<?= $dynamic_id?>';
    var commentId = '<?= $comment_id?>';
    var vestUsers = eval(<?php echo json_encode($users)?>);

    //初始化表格设置
    $('#table2').bootstrapTable({

//        height: 525,//高度
        toolbar: '#toolbar',        //工具按钮用哪个容器
        clickToSelect: true,//点击行即可选中单选/复选框
        singleSelect: false,//复选框只能选择一条记录
        search: false,//是否显示右上角的搜索框
        striped: true,      //是否显示行间隔色
        cache: false,            //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        sidePagination: "server", //服务端处理分页
        pagination: true,     //是否显示分页（*）
        sortable: false,           //是否启用排序
        sortOrder: "asc",          //排序方式
        method: 'GET',      //请求方式（*）
        pageNumber:1,      //初始化加载第一页，默认第一页
        pageSize: 10,      //每页的记录行数（*）
//        pageList: [10, 20, 50, 100],  //可供选择的每页的行数（*）
        cardView: false,          //是否显示详细视图
        onPageChange:function(){$('#table2').bootstrapTable('hideLoading');},//隐藏数据加载中
        uniqueId:'dynamic_id',
        url:'comment-data?comment_id='+commentId,
        responseHandler:dataCommentProcess,

        columns: [{
            field: '',
            align: 'center',
            valign: 'middle',
            title: '评论列表',
            formatter:function(value,row,index) {
                $('.fixed-table-body').eq(0).css('height','0px');
                $('.pull-left').eq(1).hide(); //隐藏数据加载中
            }
        }]
    });
    $('.fixed-table-container').eq(0).css('border','none');
    $('#table2').bootstrapTable('hideLoading'); //隐藏数据加载中
    function dataCommentProcess(res){
        var data = res;

        $(".comment-item-container").empty();
        var commentHtml = "";
        var comments = data.rows;
        for(var index = 0 ; index < comments.length; index ++){
            var commentData = comments[index];
            commentHtml +=initCommentData(commentData);
        }
        $(".comment-item-container").append(commentHtml);

        return {
            'rows':data.rows,
            'total':data.total
        }

    }

    function initSecondComments(secondComments){
        var secondCommentHtml = "";
        for(var index = 0 ; index < secondComments.length; index ++){
            if(index > 1)
                break;
            var commentData = secondComments[index];
            secondCommentHtml += initCommentData(commentData);
        }
        if(secondComments.length != 0 )
            secondCommentHtml += '<p class="story_hf">查看更多评论</p>';

        return secondCommentHtml;
    }

    function initCommentData(commentData){
        if(commentData.comment_level == 1)
            return '<div class="comment-item">'+
                '<img class="comment-avatar" src="'+commentData.user.user_avatar+'">'+

                '<div class="story">'+
                '<div class="opbtn" style="cursor: pointer" comment-content="'+commentData.comment_content+'" type="2" onclick="showPraiseDialog(this,'+commentData.comment_id+')"><img class="like-icon" src="<?= $base?>/app/images/dynamic/rc_icon_seduce_dynamic_details_praise.png">'+commentData.like_count+'</div>'+
                '<p class="story_t">'+getCommentUserMessage(commentData.user.user_nickname,commentData.user.user_sex,commentData.user.city_name)+ "&nbsp" +diaplayTime(commentData.gmt_create)+'</p>'+
                '<p class="story_m">'+commentData.comment_content+'</p>'+
                '<p><span class="story_r" comment-content="'+commentData.comment_content+'" onclick="showCommentDialog(this,'+commentData.comment_id+')">回复</span><span class="story_d" onclick="operateController.operateFunc('+commentData.comment_id+')">删除</span></p>'+
                initSecondComments(commentData.second_comments)+
                '</div>'+

                '<div class="clear"></div>'+
                '</div>';
        else
            return '<div class="comment-item">'+
                '<img class="comment-avatar" src="'+commentData.user.user_avatar+'">'+

                '<div class="story">'+
                '<div class="opbtn" style="cursor: pointer" comment-content="'+commentData.comment_content+'" type="2" onclick="showPraiseDialog(this,'+commentData.comment_id+')"><img class="like-icon" src="<?= $base?>/app/images/dynamic/rc_icon_seduce_dynamic_details_praise.png">'+commentData.like_count+'</div>'+
                '<p class="story_t">'+getCommentUserMessage(commentData.user.user_nickname,commentData.user.user_sex,commentData.user.city_name)+ "&nbsp" +diaplayTime(commentData.gmt_create)+'</p>'+
                '<p class="story_m">'+setThirdCommentContent(commentData)+'</p>'+
                '<p><span class="story_r" comment-content="'+commentData.comment_content+'" onclick="showCommentDialog(this,'+commentData.comment_id+')">回复</span><span class="story_d" onclick="operateController.operateFunc('+commentData.comment_id+')">删除</span></p>'+
                '</div>'+

                '<div class="clear"></div>'+
                '</div>';
    }

    function setThirdCommentContent(commentData){
        if(commentData.comment_level == 3){
            return commentData.comment_content+"//@"+commentData.target_comment.user.user_nickname +"："+commentData.target_comment.comment_content;

        }else
            return commentData.comment_content;

    }

    function getCommentUserMessage(name,sex,area){
        var userString = "";
        userString += name;

        if(sex == 0)
            userString +="（女，";
        else
            userString +="（男，";

        userString +=area + "）";

        return userString;
    }

    function diaplayTime(data) {

        var str = data;
        var result;
        //将字符串转换成时间格式
        var timePublish = new Date(str);
        var timeNow = new Date();
        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var month = day * 30;
        var diffValue = timeNow - timePublish;
        var diffMonth = diffValue / month;
        var diffWeek = diffValue / (7 * day);
        var diffDay = diffValue / day;
        var diffHour = diffValue / hour;
        var diffMinute = diffValue / minute;

        if (diffValue < 0) {
            result = "刚刚";
        }
        else if (diffMonth > 3) {
            result = timePublish.getFullYear()+"-";
            result += timePublish.getMonth() + "-";
            result += timePublish.getDate();
            alert(result);
        }
        else if (diffMonth > 1) {
            result = parseInt(diffMonth) + "月前";
        }
        else if (diffWeek > 1) {
            result = parseInt(diffWeek) + "周前";
        }
        else if (diffDay > 1) {
            result = parseInt(diffDay) + "天前";
        }
        else if (diffHour > 1) {
            result = parseInt(diffHour) + "小时前";
        }
        else if (diffMinute > 1) {
            result = parseInt(diffMinute) + "分钟前";
        }
        else {
            result = "刚刚";
        }
        return result;
    }

    var targetCommentId = null;
    var operateDialog = $("#commentDialog");

    function showCommentDialog(view,commentId){
        var commentContent = $(view).attr("comment-content");
        targetCommentId = commentId;
        operateDialog.find("p").text("评论内容："+commentContent);
        operateDialog.show();
    }

    function hideCommentDialog(){
        operateDialog.hide();
    }

    function confirmComment(){
        var userId = $("#dynamicUserId").attr("userid");
        var userToken = $("#dynamicUserId").attr("usertoken");

        var content = $("#operateContent").val().replace(/[&\|\\\*^%$#@\-]/g,"");
        if(content.length == 0){
            alert("请输入评论内容");
            return;
        }

        if(userId == undefined){
            alert("请选择马甲用户");
            return;
        }

        commentController.commentFunc(userId,userToken,targetCommentId,content);
    }

    var operateController = {
        operateApi : "operate-comment",
        operateFunc:function(comment_id){

            var confirmStr = "确认删除评论吗？";

            if(confirm(confirmStr)){
                var param = {
                    comment_id:comment_id,
                    type:1
                };

                sendAjax(this.operateApi,"POST",param,true,function(res){
                    var data = JSON.parse(res);
                    if(data.code == 0)
                        alert('删除成功');
                        $('#table2').bootstrapTable('refresh');
                });
            }

        }
    };

    var commentController = {
        commentApi : baseUrl + "Hotcity/v1/comments",
        commentFunc : function(userId,token,targetCommentId,content){
            var param = {
                user_id:userId,
                token:token,
                dynamic_id:dynamicId,
                comment_content:content
            };

            if(targetCommentId != null)
                param.target_comment_id = targetCommentId;

            sendAjax(this.commentApi,"POST",param,false,function(res){
                if(res.code != 0){
                    $("#dynamicContent").val("");
                    $("#operateContent").val("");
                    targetCommentId = null;
                    hideCommentDialog();
                    $('#table2').bootstrapTable('refresh');
                } else
                    alert(res.msg);
            });
        }
    };

    //初始化表格设置
    $('#table3').bootstrapTable({

//        height: 525,//高度
        toolbar: '#toolbar',        //工具按钮用哪个容器
        clickToSelect: true,//点击行即可选中单选/复选框
        singleSelect: false,//复选框只能选择一条记录
        search: false,//是否显示右上角的搜索框
        striped: true,      //是否显示行间隔色
        cache: false,            //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        sidePagination: "server", //服务端处理分页
        pagination: true,     //是否显示分页（*）
        sortable: false,           //是否启用排序
        sortOrder: "asc",          //排序方式
        method: 'GET',      //请求方式（*）
        pageNumber:1,      //初始化加载第一页，默认第一页
        pageSize: 18,      //每页的记录行数（*）
//        pageList: [10, 20, 50, 100],  //可供选择的每页的行数（*）
        cardView: false,          //是否显示详细视图
        onPageChange:function(){$('#table3').bootstrapTable('hideLoading');},//隐藏数据加载中
        uniqueId:'user_id',
        url:'vest-data',
        responseHandler:dataUserProcess,

        columns: [{
            field: '',
            align: 'center',
            valign: 'middle',
            title: '用户列表',
            formatter:function(value,row,index) {
                $('.fixed-table-body').eq(1).css('height','0px');
                $('.pull-left').eq(1).hide(); //隐藏数据加载中
            }
        }]
    });
    $('.fixed-table-container').eq(1).css('border','none');
    $('#table3').bootstrapTable('hideLoading'); //隐藏数据加载中

    function dataUserProcess(res){
        var result = res;

        $(".vest-box").empty();
        var html = "";
        var datas = result.rows;
        for(var index = 0 ; index < datas.length; index ++){
            var data = datas[index];
            html +='<div class="vest-item">'+
            '<img class="vest-avatar" src="'+data.user_avatar+'">'+
            '<span class="vest-message">'+getCommentUserMessage(data.user_nickname,data.user_sex,data.city_name)+'</span>'+
            '<span class="vest-choose" userid="'+data.user_id+'" usertoken="'+data.token+'" username="'+data.user_nickname+'" onclick="chooseVestInsert(this)">选择</span>'+
            '</div>';
        }
        $(".vest-box").append(html);

        return {
            'rows':result.rows,
            'total':result.total
        }

    }

    var typeUserView = "dynamicUserId";
    function showVestDialog(viewId){
        typeUserView = viewId;
        $("#chooseUser").show();
    }

    function chooseVestInsert(view){
        $("#"+typeUserView).text($(view).attr("username"));
        $("#"+typeUserView).attr("userid",$(view).attr("userid"));
        $("#"+typeUserView).attr("usertoken",$(view).attr("usertoken"));
        hideVestDialog();
    }

    function hideVestDialog(){
        $("#chooseUser").hide();
    }

    var praiseDialog = $("#praiseDialog");
    var likeType = "1";

    function showPraiseDialog(view,commentId){
        var commentContent = $(view).attr("comment-content");
        likeType = $(view).attr("type");
        targetCommentId = commentId;
        praiseDialog.find("p").text("点赞内容："+commentContent);
        praiseDialog.show();
    }

    function hidePraiseDialog(){
        praiseDialog.hide();
    }

    function confirmPraise(){
        var userId = $("#praiseUserId").attr("userid");
        var userToken = $("#praiseUserId").attr("usertoken");

        if(userId == undefined){
            alert("请选择马甲用户");
            return;
        }

        praiseController.praiseFunc(userId,userToken,"2",targetCommentId,"1");
    }

    var praiseController = {
        praiseApi : baseUrl + "Hotcity/v1/likes",
        praiseFunc : function(userId, token,likeType,tid,operateType){
            var param = {
                user_id:userId,
                token:token,
                like_type:likeType,
                tid:tid,
                o_type:operateType
            };

            sendAjax(this.praiseApi,"POST",param,false,function(res){
                if(res.code != 0){
                    targetCommentId = null;
                    hidePraiseDialog();
                    window.location.reload();
                } else
                    alert(res.msg);
            });
        }
    };
</script>
